package com.qf.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.StroageService;
import com.qf.util.ResponseUtil;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * projectName: wokepase1
 *
 * @author: 强力
 * time: 2021/9/14 16:08
 * description:
 */
@RestController
@RequestMapping("/storage")
@CrossOrigin("*")
public class StroageController {

    @Autowired
    private StroageService stroageService;

    /**
     *
     * @param page 当前页
     * @param limit 每页显示条数
     * @param key 文件key
     * @param name 文件名
     * @param sort 排序字段
     * @param order 排序方式 Asc或者Dasc
     * @return
     */
    @RequestMapping("list")
    public Object list(Integer page,Integer limit,String key,String name,String sort, String  order){
        IPage<DtsStorage> storageIPage = stroageService.findBypage(page, limit, key, name, sort, order);


        //封装返回的数据
        Map<String,Object> data=new HashMap<>();
        data.put("total",storageIPage.getTotal());
        data.put("items",storageIPage.getRecords());

        return ResponseUtil.ok(data);
    }

    /**
     * 文件上传对接oss
     * @param file
     * @return
     */
    @RequestMapping("/create")
    public Object create(@RequestParam("file") MultipartFile file) throws  Exception{

    //获取完整文件名
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)){
            throw new RuntimeException("上传文件失败,可能为空");
        }
        //获取文件扩展名
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //调用service完成上传存储
        DtsStorage storage = stroageService.insert(originalFilename, ext, (int) file.getSize(), file.getBytes());
        return ResponseUtil.ok(storage);
    }

    /**
     * 删除
     * @param storage
     * @return
     */
    @RequestMapping("/delete")
    public Object delete(@RequestBody DtsStorage storage){
        String key = storage.getKey();

        if (StringUtils.isEmpty(key)){
            throw new RuntimeException("所选项无效");
        }
            stroageService.delectByKey(key);
        return ResponseUtil.ok();
    }

    /**
     * 修改
     * @param
     * @return
     */
    @RequestMapping("/update")
    public Object update(@RequestBody DtsStorage storage){

        int i = stroageService.updateFile(storage);
        if (i == 0){
            return new RuntimeException("更新超级失败");
        }
return ResponseUtil.ok(storage);

    }
}

